package com.android.citynetworkpin.fragment.group;

import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.citynetworkpin.R;
import com.android.citynetworkpin.fragment.BaseLazyFragment;
import com.android.citynetworkpin.model.group.MainThematicActivity_Insert;
import com.android.citynetworkpin.model.group.SecondKillData;
import com.android.citynetworkpin.model.group.SecondKillDataCallback;
import com.android.citynetworkpin.utils.ConstantsUrl;
import com.android.citynetworkpin.utils.HttpUtils;
import com.android.citynetworkpin.utils.ObjectUtils;
import com.android.citynetworkpin.view.group.VRefreshLayout;
import com.android.citynetworkpin.view.recycleview.CustomLoadMoreView;
import com.android.citynetworkpin.view.recycleview.CustomRecycleView;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


/**
 * Created by Administrator on 2017/7/5.
 */

public class Fragment_LTSecondKill extends BaseLazyFragment implements BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.listView)
    CustomRecycleView mRecyclerView;
    @BindView(R.id.swipe_refresh_layout)
    VRefreshLayout mRefreshLayout;
    @BindView(R.id.click_resetnetwork)
    LinearLayout clickResetnetwork;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.no_data_tv)
    TextView noDataTv;
    @BindView(R.id.no_data)
    RelativeLayout noData;
    @BindView(R.id.progress_loading)
    FrameLayout progressLoading;

    private View rootView;
    private AdaptList adapter;
    private LayoutInflater inflater;
    private boolean networkConnected;
    private FragmentActivity mcontext;
    private static final String ARG_PARAM1 = "time";
    private static final String ARG_PARAM2 = "position";
    private static final String ARG_PARAM3 = "sortID";
    private int time;
    private int page;
    private TextView kill_hour;
    private TextView kill_minute;
    private TextView kill_second;
    private boolean isRunning = true;
    private ArrayList<MainThematicActivity_Insert.DataBean.ListBean> ta_insert = new ArrayList<>();
    private ArrayList<SecondKillData.DataBean.ListBean> listdata = new ArrayList<>();
    private View inflate;
    private TextView refresh_textView;
    private int position;
    private String sortID;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            time = getArguments().getInt(ARG_PARAM1);
            position = getArguments().getInt(ARG_PARAM2);
            sortID = getArguments().getString(ARG_PARAM3);
            if(position==0) {
                new Thread() {
                    @Override
                    public void run() {
                        while (isRunning) {
                            SystemClock.sleep(1000);

                            handler1.sendEmptyMessage(1);
                        }
                    }
                }.start();
            }
        }
    }

    private Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 1) {
                if (time > 0) {
                    String hour = String.format("%02d", time / 3600);
                    String minute = String.format("%02d", time % 3600 / 60);
                    String second = String.format("%02d", time % 60);
                    kill_hour.setText(hour);
                    kill_minute.setText(minute);
                    kill_second.setText(second);
                    time--;
                }
            }
        }
    };

    public static Fragment_LTSecondKill newInstance(int time, int position, String sortID) {
        Fragment_LTSecondKill fragment = new Fragment_LTSecondKill();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, time);
        args.putInt(ARG_PARAM2, position);
        args.putString(ARG_PARAM3, sortID);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initPrepare() {
        ReFreshData();
    }

    private LinearLayoutManager mLayoutManager;
    private GridLayoutManager mGridLayoutManager;

    @Override
    protected void onInvisible() {

    }

    @Override
    protected void initData() {
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        if (networkConnected) {
            page = 1;
//            getMianThematic_Insert();
            GetListData(page);
        } else {
            ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
        }
    }

    @Override
    protected View initView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.inflater = inflater;
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        rootView = inflater.inflate(R.layout.layout_ltsecondkill, container, false);
        ButterKnife.bind(this, rootView);
        mcontext = getActivity();
        initRecycle();
        return rootView;
    }

    private void initRecycle() {
        adapter = new AdaptList(mcontext, ta_insert, null, "0");
        adapter.setLoadMoreView(new CustomLoadMoreView());
        adapter.setOnLoadMoreListener(this, mRecyclerView);
        if(position==0){
            View fragment_head = inflater.inflate(R.layout.second_kill_head_banner, null, false);
            kill_hour = (TextView) fragment_head.findViewById(R.id.kill_hour);
            kill_minute = (TextView) fragment_head.findViewById(R.id.kill_minute);
            kill_second = (TextView) fragment_head.findViewById(R.id.kill_second);
            String hour = String.format("%02d", time / 3600);
            String minute = String.format("%02d", time % 3600 / 60);
            String second = String.format("%02d", time % 60);
            kill_hour.setText(hour);
            kill_minute.setText(minute);
            kill_second.setText(second);
            adapter.addHeaderView(fragment_head);
        }
        mLayoutManager = new LinearLayoutManager(mcontext);
        mGridLayoutManager = new GridLayoutManager(mcontext, 2);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.GetToTop((ImageView) rootView.findViewById(R.id.top), 0);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter1, View view, int position) {
                //  ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
            }
        });
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public boolean onItemChildClick(BaseQuickAdapter adapter1, View view, int position) {
                switch (view.getId()) {
                    case R.id.gotoshop_ll:
                        ObjectUtils.ToDetailActivity(mcontext, 1, adapter.getItem(position).getId(), "");
                        break;
                }
                return false;
            }
        });
    }

    private void ReFreshData() {
        if (mRefreshLayout != null) {
            mRefreshLayout.setBackgroundColor(Color.TRANSPARENT);
            mRefreshLayout.setAutoRefreshDuration(400);
            mRefreshLayout.setRatioOfHeaderHeightToReach(1.5f);
            mRefreshLayout.addOnRefreshListener(new VRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    networkConnected = ObjectUtils.isNetworkConnected(mcontext);
                    if (networkConnected) {
                        mRefreshLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mRefreshLayout.refreshComplete();
                                page = 1;
                                GetListData(page);
                            }
                        }, 1000);
                    } else {
                        ObjectUtils.toast(mcontext, "网络连接出现异常");
                    }
                }
            });
        }
    }

    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.click_resetnetwork_refresh:
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 3);
                page = 1;
//                getMianThematic_Insert();
                GetListData(page);
                break;
        }
    }

    @Override
    public void onLoadMoreRequested() {
        page = page + 1;
        GetListData(page);
    }

    /**
     * 专题活动插入信息
     */
//    private void getMianThematic_Insert() {
//        String address = ConstantsUrl.domain + ConstantsUrl.MAINTHMATIC_INSERT;
//        HashMap<String, String> map = new HashMap<>();
//        map.put("posid", "4");
//        HttpUtils.get(address, map, new MainThematicActivity_InsertCallback() {
//            @Override
//            public void onError(Call call, Exception e, int id) {
//
//            }
//
//            @Override
//            public void onResponse(MainThematicActivity_Insert response, int id) {
//                ta_insert.clear();
//                if (response == null) {
//                    return;
//                }
//                MainThematicActivity_Insert.DataBean data = response.getData();
//                if (data != null && ObjectUtils.listHasData(data.getList())) {
//                    ta_insert.addAll(data.getList());
//                    mRecyclerView.setLayoutManager(mLayoutManager);
//                    mRecyclerView.setAdapter(adapter);
//                }
//            }
//        });
//    }

    private void GetListData(final int page) {
        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.SECONDKILL;
            HashMap<String, String> map = new HashMap<>();
            map.put("page", page + "");
            if(position==1){
                map.put("time", "well");
            }else {
                if(!TextUtils.isEmpty(sortID)){
                    map.put("order", "goods_id");
                    map.put("sort", sortID+"");
                }
            }
            HttpUtils.get(address, map, new SecondKillDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
                }

                @Override
                public void onResponse(SecondKillData response, int id) {
                    if (response == null) {
                        ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
                        return;
                    }
                    ObjectUtils.GetDataNet(clickResetnetwork, progress, 1);
                    if (response.getCode() == 0) {
                        SecondKillData.DataBean data = response.getData();
                        if (data == null || !ObjectUtils.listHasData(data.getList())) {
                            if (page == 1) {
                                noData.setVisibility(View.VISIBLE);
                            } else {
                                adapter.loadMoreEnd();
                            }
                            return;
                        }
                        time = data.getEtime();
                        listdata = new ArrayList<>();
                        listdata.addAll(data.getList());
                        if (page == 1) {
                            adapter.setNewData(listdata);
                        } else {
                            adapter.addData(listdata);
                            adapter.loadMoreComplete();
                        }
                    } else {
                        if (page == 1) {
                            noData.setVisibility(View.VISIBLE);
                        } else {
                            adapter.loadMoreFail();
                            ObjectUtils.toast(mcontext, response.getMsg());
                        }
                    }
                }
            });
        } else {
            if (page == 1) {
                ObjectUtils.GetDataNet(clickResetnetwork, progress, 2);
            }
            ObjectUtils.toast(getActivity(), "网络连接出现异常");
            adapter.loadMoreFail();
        }
    }

    public class AdaptList extends BaseMultiItemQuickAdapter<SecondKillData.DataBean.ListBean, BaseViewHolder> {
        private String type;
        private ArrayList<MainThematicActivity_Insert.DataBean.ListBean> ta_insert;
        private FragmentActivity mcontext;
        private int limitposition;

        public AdaptList(FragmentActivity context, ArrayList<MainThematicActivity_Insert.DataBean.ListBean> ta_insert, List<SecondKillData.DataBean.ListBean> data, String type) {
            super(data);
            //  this.datasize = data.size();
            this.mcontext = context;
            this.type = type;
            this.ta_insert = ta_insert;
            addItemType(ConstantsUrl.THEMATICGOODSLISTItemTYPE, R.layout.second_kill_list_main);
        }

        @Override
        protected void convert(BaseViewHolder holder, SecondKillData.DataBean.ListBean mainlistdata) {
            switch (holder.getItemViewType()) {
                case ConstantsUrl.THEMATICGOODSLISTItemTYPE:
                    ObjectUtils.photo2(mContext, mainlistdata.getThumb(), ((ImageView) holder.getView(R.id.main_list_item_image)));
                    holder.setText(R.id.item_name, mainlistdata.getName());
                    holder.setText(R.id.item_grid_detail_like_recommend, mainlistdata.getDesc());
                    holder.setText(R.id.item_list_sort_aa_total, "￥" + mainlistdata.getTeam_price());
                    ((TextView) holder.getView(R.id.item_list_sort_aa_before)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    String price1 = mainlistdata.getPrice();
                    SpannableString msp = new SpannableString("￥" + price1);
                    msp.setSpan(new AbsoluteSizeSpan(13, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    holder.setText(R.id.item_list_sort_aa_before, msp);
                    holder.setText(R.id.main_list_tuannumber, "已抢" + mainlistdata.getSell() + "件");
                    holder.setText(R.id.skill_scale, mainlistdata.getScale() + "%");
                    ProgressBar bar = (ProgressBar) holder.getView(R.id.progressBar_kill);
                    bar.setProgress(mainlistdata.getScale());
                    // bar.setBackgroundColor(R.color.app_title);
                    /**
                     * 插入专题活动
                     */

//                    final int taposition = holder.getAdapterPosition();
//                    limitposition = 3 * ta_insert.size();
//                    if (mcontext instanceof FragmentActivity) {
//                        if (taposition % 3 == 0 && taposition <= limitposition) {
//
//                            holder.getView(R.id.ll_tainsert).setVisibility(View.VISIBLE);
//                            holder.getView(R.id.progress_hot).setVisibility(View.INVISIBLE);
//                            TextView more_tv = (TextView) holder.getView(R.id.more_tv);
                            //水平滚动列表
//                            NestFullListView tabrow = (NestFullListView) holder.getView(R.id.grid);
//                            //        //动态设置选项卡宽度，超过2个可以滑动查看
//                            DisplayMetrics metrics = new DisplayMetrics();
//                            mcontext.getWindowManager().getDefaultDisplay().getMetrics(metrics);
//                            final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(metrics.widthPixels / 2, LinearLayout.LayoutParams.MATCH_PARENT);
//                            tabrow.setAdapter(new NestFullListViewAdapter<MainThematicActivity_Insert.DataBean.ListBean.ApplyBean>(R.layout.list_main_hor_adapter, ta_insert.get(taposition / 3 - 1).getApply_list()) {
//                                @Override
//                                public void onBind(int position, MainThematicActivity_Insert.DataBean.ListBean.ApplyBean testBean, NestFullViewHolder holder) {
//                                    (holder.getView(R.id.item_grid_detail_like_ll)).setLayoutParams(params);
//                                    ((TextView) holder.getView(R.id.item_grid_detail_like_number_before)).getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
//                                    String price1 = testBean.getTeam_price();
//                                    SpannableString msp = new SpannableString("￥" + price1);
//                                    msp.setSpan(new AbsoluteSizeSpan(10, true), 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//                                    ((TextView) holder.getView(R.id.item_grid_detail_like_number_after)).setText(msp);
//                                    holder.setText(R.id.item_grid_detail_like_number_before, "￥" + testBean.getPrice());
//                                    holder.setText(R.id.item_grid_detail_like_title, testBean.getName());
//                                    ObjectUtils.photo2(mcontext, testBean.getImg_cover(), ((ImageView) holder.getView(R.id.item_grid_detail_like_img)));
//
//                                }
//                            });
//
//                            tabrow.setOnItemClickListener(new NestFullListView.OnItemClickListener() {
//                                @Override
//                                public void onItemClick(NestFullListView nestFullListView, View view, int pos) {
//                                    ObjectUtils.ToDetailActivity(mcontext, 1, ta_insert.get(taposition / 3 - 1).getApply_list().get(pos).getGoods_id(), "");
//                                }
//                            });
//                            more_tv.setOnClickListener(new View.OnClickListener() {
//                                @Override
//                                public void onClick(View view) {
//                                    Intent intent = new Intent(mcontext, BaseObject.class);
//                                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, ta_insert.get(taposition / 3 - 1).getId());
//                                    intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, "专题活动");
//                                    mcontext.startActivity(intent);
//                                }
//                            });
//
//                        } else {
//                            holder.getView(R.id.ll_tainsert).setVisibility(View.GONE);
//                        }
//                    }
                    holder.addOnClickListener(R.id.gotoshop_ll);
                    break;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isRunning = false;
    }
}
